package hk.hku.hooku.servlet;

import hk.hku.hooku.db.EventDB;
import hk.hku.hooku.pojo.EventChoice;
import hk.hku.hooku.pojo.EventResult;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * Servlet implementation class GetHistory
 */
public class GetHistoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetHistoryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String url=request.getParameter("url");
		//String link=request.getParameter("eventlink");
		System.out.println("new");

		//url="test";
		PrintWriter writer=response.getWriter();
		//writer.write("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
		
		if(url!=null){
			String email=request.getParameter("voterEmail");
			String getchoices=request.getParameter("allchoices");
			//email="loengf@hku.hk";
			int currentEventId=EventDB.getIdByUrl(url);
			System.out.println("currentId");
			System.out.println(currentEventId);
			ArrayList<Integer> historyEventIds=new ArrayList<Integer>();
			historyEventIds=EventDB.checkHistoryEvent(email);
			//System.out.println("lllllllllllllllllllllllllllllllll");
			//PrintWriter writer=response.getWriter();
			//System.out.println(historyEventIds);
			
			//for test to remove currenteventId
			//historyEventIds.remove(0);
			System.out.println("historyId");
			System.out.println(historyEventIds);
			
			if(!historyEventIds.isEmpty()){
				ArrayList<Integer> finalhistoryEventIds=findHistoryEvent(currentEventId,historyEventIds);
				ArrayList<EventChoice> currentEventChoices=EventDB.getEventChoices(currentEventId);
				System.out.println(currentEventChoices);
				int choicenumber=currentEventChoices.size();
				boolean [] finalChoiceFlags = new boolean [choicenumber];
				
				for(int i=0;i<choicenumber;i++){
					finalChoiceFlags[i]=false;
					System.out.println(finalChoiceFlags[i]);
				}
				//System.out.println(currentEventChoices);

				if(!finalhistoryEventIds.isEmpty()){
					System.out.println("history");
					ArrayList<Integer> historyVoteIds=new ArrayList<Integer>();
					for(int tempeventId:finalhistoryEventIds){
						int historyvoteId=EventDB.checkHistoryVote(email,tempeventId);
						System.out.println(currentEventChoices.get(0).getStartTime());
						historyVoteIds.add(historyvoteId);
						System.out.println(historyvoteId);
						//ArrayList<EventChoice> historyEventChoices=EventDB.getEventChoices(tempeventId);
						ArrayList<Integer> historychoiceIds=EventDB.getVoteChoices(historyvoteId);
						System.out.println(historychoiceIds);
						ArrayList<EventChoice> historychoices=EventDB.getChoices(historychoiceIds);
						System.out.println(historychoices);
						ArrayList<EventChoice> historyInterval=new ArrayList<EventChoice>();
						historyInterval=gethistoryInterval(historychoices);
						
					    // testing
						/*
						for(EventChoice each:historyInterval){
						 System.out.println(each.getStartTime());
						 System.out.println(each.getEndTime());
						 }
						*/
						int tempsize=historyInterval.size();
						System.out.println("\n"+String.valueOf(tempsize));
						// compare the history time interval with current time interval
						int tempindex=0;
						for(EventChoice currentChoice:currentEventChoices){
							System.out.println("eachcureentchoice555555555555");
							int tempid=currentChoice.getId();
							for(EventChoice historyinterval:historyInterval){
								//System.out.println(tempindex);
								//System.out.println(finalChoiceFlags[tempindex]);
								
								if(timeCompare(currentChoice,historyinterval)){
									finalChoiceFlags[tempindex]=true;
								}
								//System.out.println(finalChoiceFlags[tempindex]);
							}
							tempindex=tempindex+1;
							//test
							/*
							for(boolean eachone:finalChoiceFlags){
								System.out.println(eachone);
							}
							*/
							

						}//for
					}// for
					String finalchoices="";
					
					for(boolean eachFlag:finalChoiceFlags){
						if(eachFlag){
							finalchoices=finalchoices+'t';
						}
						else{
							finalchoices=finalchoices+'f';
						}
					}
					System.out.println("hey, I am new");
					System.out.println(finalchoices);
					writer.write(finalchoices);

				}//if
			}//if
			else{
				writer.write("empty");
			}
		}//if

		

   }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	protected ArrayList<EventChoice> gethistoryInterval(ArrayList<EventChoice> historyChoices){
		ArrayList<EventChoice> historyInterval=new ArrayList<EventChoice>();
		EventChoice newfirstinterval=new EventChoice();
		newfirstinterval.setStartTime(historyChoices.get(0).getStartTime());
		newfirstinterval.setEndTime(historyChoices.get(0).getEndTime());
		historyInterval.add(newfirstinterval);
		int len= historyChoices.size();
		int firstindex=1;
		
		for(firstindex=1;firstindex<=len-1;firstindex++){
			EventChoice temp=historyChoices.get(firstindex);
			//String tempstart=StartTimeformat(temp);
			//String tempend=EndTimeformat(temp);
			Timestamp tempstart=temp.getStartTime();
			Timestamp tempend=temp.getEndTime();
			int tempsize=historyInterval.size();
			int templastindex=tempsize-1;
			EventChoice tempinterval=historyInterval.get(templastindex);
			//String tempintervalstart=StartTimeformat(tempinterval);
			//String tempintervalend=EndTimeformat(tempinterval);
			Timestamp tempintervalstart=tempinterval.getStartTime();
			Timestamp tempintervalend=tempinterval.getEndTime();
            //System.out.println("\n"+tempend);
            //System.out.println("\n"+tempintervalstart);
            //System.out.println("\n"+tempintervalend);
			if(tempstart==tempintervalend){
				tempinterval.setEndTime(temp.getEndTime());
				historyInterval.set(templastindex,tempinterval);
				
			}
			else{
				
				EventChoice newinterval=new EventChoice();
				newinterval.setStartTime(temp.getStartTime());
				newinterval.setEndTime(temp.getEndTime());
				historyInterval.add(newinterval);
				}

		}
		return historyInterval;
	}
	
	
    protected ArrayList<Integer> findHistoryEvent(int currentEventId, ArrayList<Integer> historyEventIds){
    	Timestamp currentcreatTime=EventDB.getCreatTimebyEventId(currentEventId);
    	//int date=currentcreatTime.getDate();//1-31
    	//int month=currentcreatTime.getMonth();
    	//int day=currentcreatTime.getDay();
    	long time=currentcreatTime.getTime();
    	ArrayList<Integer> finalhistoryEventIds=new ArrayList<Integer>();
    	for(int id:historyEventIds){
    		Timestamp tempcreatTime=EventDB.getCreatTimebyEventId(id);
    		if(tempcreatTime!=null){
    			long temptime=tempcreatTime.getTime();
            	long timediff=temptime-time;
            	System.out.println(timediff);
            	if(timediff<=1000*8*24*60*60){
            		finalhistoryEventIds.add(id);
            		System.out.println("within the week");
    			}
        	
        	}
    	}
    	//System.out.println(finalhistoryEventIds);
		return finalhistoryEventIds;
    }	
	
    protected String StartTimeformat(EventChoice tempinterval){
		String tempintervalstart=String.format("%02d", tempinterval.getStartTime().getHours())+':'+String.format("%02d", tempinterval.getStartTime().getMinutes())+':'+String.format("%02d", tempinterval.getStartTime().getSeconds());
	    return tempintervalstart;
    }
    
    protected String EndTimeformat(EventChoice tempinterval){
  		String tempintervalend=String.format("%02d", tempinterval.getEndTime().getHours())+':'+String.format("%02d", tempinterval.getEndTime().getMinutes())+':'+String.format("%02d", tempinterval.getEndTime().getSeconds());
  	    return tempintervalend;
      }
    
    protected boolean timeCompare(EventChoice currentChoice, EventChoice historyinterval){
    	System.out.println("compare time");
    	int tempStartDate=historyinterval.getStartTime().getDay();
    	int tempEndDate=historyinterval.getEndTime().getDay();
    	int tempHistoryIntervalStartTimeHour=historyinterval.getStartTime().getHours();
    	int tempHistoryIntervalStartTimeMin=historyinterval.getStartTime().getMinutes();
    	int tempHistoryIntervalStartTimeSec=historyinterval.getStartTime().getSeconds();
    	int tempHistoryIntervalEndTimeHour=historyinterval.getEndTime().getHours();
    	int tempHistoryIntervalEndTimeMin=historyinterval.getEndTime().getMinutes();
    	int tempHistoryIntervalEndTimeSec=historyinterval.getEndTime().getSeconds();
		
    	int currentStartDate=currentChoice.getStartTime().getDay();
    	int currentEndDate=currentChoice.getEndTime().getDay();
    	int currentChoiceStartTimeHour=currentChoice.getStartTime().getHours();
    	int currentChoiceStartTimeMin=currentChoice.getStartTime().getMinutes();
    	int currentChoiceStartTimeSec=currentChoice.getStartTime().getSeconds();
    	int currentChoiceEndTimeHour=currentChoice.getEndTime().getHours();
    	int currentChoiceEndTimeMin=currentChoice.getEndTime().getMinutes();
    	int currentChoiceEndTimeSec=currentChoice.getEndTime().getSeconds();
    	boolean start=false;
    	boolean end=false;
    	/*
    	System.out.println(tempStartDate);
    	System.out.println(historyinterval.getStartTime());
    	System.out.println(historyinterval.getEndTime());
    	
    	System.out.println(currentStartDate);
    	System.out.println(currentChoice.getStartTime());
    	System.out.println(currentChoice.getEndTime());
    	*/
    	if(tempStartDate==currentStartDate){
    		
        	// compare starttime
        	if(tempHistoryIntervalStartTimeHour<currentChoiceStartTimeHour){
        		start=true;
        	}
        	if(tempHistoryIntervalStartTimeHour==currentChoiceStartTimeHour && tempHistoryIntervalStartTimeMin<currentChoiceStartTimeMin){
        		start=true;
        	}
        	if (tempHistoryIntervalStartTimeHour==currentChoiceStartTimeHour && tempHistoryIntervalStartTimeMin==currentChoiceStartTimeMin && tempHistoryIntervalStartTimeSec<=currentChoiceStartTimeSec){
        		start=true;
        	}
        	
        	// compare endtime
        	if(tempHistoryIntervalEndTimeHour>currentChoiceEndTimeHour){
        		end=true;
        	}
        	if(tempHistoryIntervalEndTimeHour==currentChoiceEndTimeHour && tempHistoryIntervalStartTimeMin>currentChoiceEndTimeMin){
        		end=true;
        	}
        	if (tempHistoryIntervalEndTimeHour==currentChoiceEndTimeHour && tempHistoryIntervalEndTimeMin==currentChoiceStartTimeMin && tempHistoryIntervalEndTimeSec>=currentChoiceEndTimeSec){
        		end=true;
        	}
        	
        	
        	
    	}
    	System.out.println(start&&end);
    	return start&&end;
   
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	}
	

}
